package com.papercutting.platform.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * Jackson配置类 - 处理日期时间序列化和反序列化
 */
@Configuration
public class JacksonConfig {

    /**
     * 日期时间格式
     */
    private static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    
    /**
     * 自定义ObjectMapper
     */
    @Bean
    @Primary
    public ObjectMapper objectMapper() {
        return Jackson2ObjectMapperBuilder.json()
                .modules(javaTimeModule())
                .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
                .build();
    }
    
    /**
     * Java时间模块配置
     */
    @Bean
    public JavaTimeModule javaTimeModule() {
        JavaTimeModule module = new JavaTimeModule();
        
        // 配置LocalDateTime的序列化和反序列化
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_TIME_FORMAT);
        module.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(formatter));
        module.addDeserializer(LocalDateTime.class, new CustomLocalDateTimeDeserializer());
        
        return module;
    }
    
    /**
     * 自定义LocalDateTime反序列化器，支持多种格式
     */
    public static class CustomLocalDateTimeDeserializer extends LocalDateTimeDeserializer {
        
        public CustomLocalDateTimeDeserializer() {
            super(DateTimeFormatter.ofPattern(DATE_TIME_FORMAT));
        }
        
        @Override
        protected LocalDateTime _fromString(com.fasterxml.jackson.core.JsonParser p, 
                                          com.fasterxml.jackson.databind.DeserializationContext ctxt, 
                                          String string) throws java.io.IOException {
            try {
                // 首先尝试标准格式
                return LocalDateTime.parse(string, DateTimeFormatter.ofPattern(DATE_TIME_FORMAT));
            } catch (Exception e1) {
                try {
                    // 尝试ISO格式（如：2025-09-11T11:33:54）
                    return LocalDateTime.parse(string, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
                } catch (Exception e2) {
                    try {
                        // 尝试带毫秒的格式
                        return LocalDateTime.parse(string, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
                    } catch (Exception e3) {
                        try {
                            // 尝试只有日期的格式
                            return LocalDateTime.parse(string + " 00:00:00", DateTimeFormatter.ofPattern(DATE_TIME_FORMAT));
                        } catch (Exception e4) {
                            // 如果都失败了，抛出原始异常
                            return super._fromString(p, ctxt, string);
                        }
                    }
                }
            }
        }
    }
}
